package com.pym.bs.handler;

import com.pym.bs.utils.GsonUtils;
import com.pym.bs.utils.ResultVOUtils;
import com.pym.bs.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("myLogoutSuccessHandler")
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private ConsumerTokenServices consumerTokenServices;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        System.out.println("登出");
        String accessToken = getAccessToken(httpServletRequest);
        consumerTokenServices.revokeToken(accessToken);
        ResultVO resultVO = ResultVOUtils.success();
        String error = GsonUtils.toJson(resultVO);
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(error);
    }

    private String getAccessToken(HttpServletRequest httpServletRequest) {
        String header = httpServletRequest.getHeader("Authorization");
        return header.substring(header.indexOf("Bearer ") + 7);
    }
}
